package com.zhang.novel.core.config;

import com.zhang.novel.core.filter.NovelFilter;
import com.zhang.novel.core.filter.XssFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

/**
 * 过滤器配置类
 */
@Configuration
public class FilterConfig {

    @Value("${pic.save.path}")
    private String picSavePath;

    @Value("${xss.enabled}")
    private String enabled;

    @Value("${xss.excludes}")
    private String excludes;

    @Value("${xss.urlPatterns}")
    private String urlPatterns;

    @Bean
    public FilterRegistrationBean<NovelFilter> novelFilterRegistration(){
        FilterRegistrationBean<NovelFilter> novelFilterRegistration=new FilterRegistrationBean<>();
        novelFilterRegistration.setFilter(new NovelFilter());
        novelFilterRegistration.addUrlPatterns("/*");
        novelFilterRegistration.addInitParameter("picSavePath",picSavePath);

        return novelFilterRegistration;
    }

    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistration(){
        FilterRegistrationBean<XssFilter> xssFilterRegistration=new FilterRegistrationBean<>();
        xssFilterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
        xssFilterRegistration.setFilter(new XssFilter());
        xssFilterRegistration.addUrlPatterns(StringUtils.split(urlPatterns,","));
        xssFilterRegistration.setName("xssFilter");
        xssFilterRegistration.setOrder(Integer.MAX_VALUE);

        Map<String,String> initParameters=new HashMap<>(2);
        initParameters.put("excludes",excludes);
        initParameters.put("enabled",enabled);
        xssFilterRegistration.setInitParameters(initParameters);

        return xssFilterRegistration;
    }
}
